package com.dunke.utils;

import com.dunke.core.data.IpAddrData;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * IP地址解析工具
 */
public class IpServletUtils {

    /**
     * 腾讯接口：http://ip.qq.com/cgi-bin/searchip?searchip1=
     * 新浪接口：http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=
     * 淘宝接口：http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串]
     * http://freeapi.ipip.net/
     */

    private static final String IP_URL = "http://freeapi.ipip.net/";

    /**
     * 提取IP地址
     */
    private static final String[] HEADERS_TO_TRY = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR",
            "HTTP_X_FORWARDED",
            "HTTP_X_CLUSTER_CLIENT_IP",
            "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR",
            "HTTP_FORWARDED",
            "HTTP_VIA",
            "REMOTE_ADDR",
            "X-Real-IP"};

    /***
     * 获取客户端ip地址(可以穿透代理)
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

    public static void main(String[] args) {
//        System.out.println("解析IP" + getIpData("221.226.35.18"));
    }

    /**
     * 创建链接，获取IP地址库数据
     * @param ip
     * @return
     * @throws IOException
     */
    public static IpAddrData getIpData(String ip) {
        IpAddrData data = new IpAddrData();
        data.setIp(ip);
        String s = HttpClientUtil.doGet(IP_URL + ip, "UTF-8");
        if (StringUtils.isBlank(s)) {
            return data;
        }
        List<String> array = new Gson().fromJson(s, ArrayList.class);
        data.setProvince(array.get(1));
        data.setCity(array.get(2));
//        System.out.println("解析IP" + array.get(2));
        return data;
    }

}
